package bookstudytest.socket;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

/**
 * @Auther: Lee
 * @Date: 2018/6/21 17:05
 * @Description: UDP方式socket
 */
public class SocketServerUDPDemo {
    public static void main(String[] args) {
        try {

            //创建服务器端
            DatagramSocket socket = new DatagramSocket(9554);
            byte[] a = new byte[1024];
            //创建数据包 接受客户端发送的数据
            DatagramPacket packet = new DatagramPacket(a,a.length);
            //接受客户端发送的数据
            socket.receive(packet);
            //读取数据
            String info = new String(a,0,a.length);
            System.out.println(info);

            //返回数据给客户端
            //得到客户端地址
            InetAddress address = packet.getAddress();
            int port = packet.getPort();
            byte[] bytes = "欢迎你".getBytes();
            //创建数据报
            DatagramPacket datagramPacket = new DatagramPacket(bytes,0,bytes.length,address,port);
            //返回给客户端
            socket.send(datagramPacket);
            socket.close();
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
